home *** CD-ROM | disk | FTP | other *** search
/ Game.EXE 2001 January / Game.EXE_01_2001.iso / demos / Blade of Darkness / data1.cab / Program_Executable_Files / Lib / PythonLib / getpass.py < prev    next >
Encoding:
Python Source  |  2000-11-16  |  2.0 KB  |  89 lines

  1. """Utilities to get a password and/or the current user name.
  2.  
  3. getpass(prompt) - prompt for a password, with echo turned off
  4. getuser() - get the user name from the environment or password database
  5.  
  6. Authors: Piers Lauder (original)
  7.          Guido van Rossum (Windows support and cleanup)
  8. """
  9.  
  10.  
  11. def getpass(prompt='Password: '):
  12.     """Prompt for a password, with echo turned off.
  13.  
  14.     Restore terminal settings at end.
  15.  
  16.     On Windows, this calls win_getpass(prompt) which uses the
  17.     msvcrt module to get the same effect.
  18.  
  19.     """
  20.  
  21.     import sys
  22.     try:
  23.         import termios, TERMIOS
  24.     except ImportError:
  25.         try:
  26.             import msvcrt
  27.         except ImportError:
  28.             return default_getpass(prompt)
  29.         else:
  30.             return win_getpass(prompt)
  31.  
  32.     fd = sys.stdin.fileno()
  33.     old = termios.tcgetattr(fd)    # a copy to save
  34.     new = old[:]
  35.  
  36.     new[3] = new[3] & ~TERMIOS.ECHO    # 3 == 'lflags'
  37.     try:
  38.         termios.tcsetattr(fd, TERMIOS.TCSADRAIN, new)
  39.         try: passwd = raw_input(prompt)
  40.         except KeyboardInterrupt: passwd = None
  41.     finally:
  42.         termios.tcsetattr(fd, TERMIOS.TCSADRAIN, old)
  43.  
  44.     sys.stdout.write('\n')
  45.     return passwd
  46.  
  47.  
  48. def win_getpass(prompt='Password: '):
  49.     """Prompt for password with echo off, using Windows getch()."""
  50.     import msvcrt
  51.     for c in prompt:
  52.         msvcrt.putch(c)
  53.     pw = ""
  54.     while 1:
  55.         c = msvcrt.getch()
  56.         if c == '\r' or c == '\n':
  57.             break
  58.         if c == '\b':
  59.             pw = pw[:-1]
  60.         else:
  61.             pw = pw + c
  62.     msvcrt.putch('\r')
  63.     msvcrt.putch('\n')
  64.     return pw
  65.  
  66.  
  67. def default_getpass(prompt='Password: '):
  68.     return raw_input(prompt)
  69.  
  70.  
  71. def getuser():
  72.     """Get the username from the environment or password database.
  73.  
  74.     First try various environment variables, then the password
  75.     database.  This works on Windows as long as USERNAME is set.
  76.  
  77.     """
  78.  
  79.     import os
  80.  
  81.     for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
  82.         user = os.environ.get(name)
  83.         if user:
  84.             return user
  85.  
  86.     # If this fails, the exception will "explain" why
  87.     import pwd
  88.     return pwd.getpwuid(os.getuid())[0]
  89.